package chapter1.socket.task1;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Task3_Server {
    public static void main(String[] args) {    
        Scanner input = new Scanner(System.in);
        try {
            ServerSocket st = new ServerSocket(9999);
            while (true) {
                Socket socket = st.accept();
                System.out.print("请输入文件名：");
                String fileName = input.next();
                new FileReceive(socket, fileName).start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}


class FileReceive extends Thread {  
    private Socket socket;
    private String fileName;

    public FileReceive(Socket socket, String fileName) {
        this.socket = socket;
        this.fileName = fileName;
    }

    @Override
    public void run() {
        try {
            InputStream in = socket.getInputStream();
            PrintWriter out2 = new PrintWriter(socket.getOutputStream(), true);
            out2.println(fileName);
            if (in.read() == 0)
                return;
            FileOutputStream out = new FileOutputStream(new File("F:\\123\\11", fileName));
            byte[] b = new byte[1024];
            int len;
            while ((len = in.read(b)) > -1)
                out.write(b, 0, len);
            out2.println("服务器接收文件，并保存成功");
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }

    }
}
